package com.lianxi.Courses.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lianxi.Courses.constant.DictConstant;
import com.lianxi.Courses.constant.StatusConstant;
import com.lianxi.Courses.dao.GoldPointsMapper;
import com.lianxi.Courses.dao.ResourceMapper;
import com.lianxi.Courses.dao.UserMapper;
import com.lianxi.Courses.dao.UserResourceMapper;
import com.lianxi.Courses.entity.*;
import com.lianxi.Courses.exception.*;
import com.lianxi.Courses.service.GoldPointsService;
import com.lianxi.Courses.service.UserResourceService;
import com.lianxi.Courses.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 翔哥
 * 2025年10月14日
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class UserResourceServiceImpl implements UserResourceService {

    @Autowired
    private UserResourceMapper userResourceMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private GoldPointsMapper goldPointsMapper;

    @Autowired
    private GoldPointsService goldPointsService;
    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<UserResource> findPage(String userId, String pageNo, String pageSize) {

        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.RESOURCE_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.RESOURCE_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<UserResource> userResources = userResourceMapper.selectAll(Integer.parseInt(userId));

        //获取单独的年和时间
        for (UserResource userResource : userResources) {

            String createDateStr = userResource.getResource().getCreateDate();
            if (createDateStr != null) {

                String[] dateTimeParts = createDateStr.split(" ");
                String datePart = dateTimeParts[0]; // "yyyy-MM-dd"
                String timePart = dateTimeParts.length > 1 ? dateTimeParts[1] : "";

                String[] dateParts = datePart.split("-");

                userResource.setYear(dateParts[0] + "年");

                userResource.setDay(dateParts[1] + "月" + dateParts[2] + "日 " + timePart);
            }
        }

        PageInfo<UserResource> userResourcePage = new PageInfo<>(userResources);
        return userResourcePage;
    }

    @Override
    public PageInfo<Resource> findMy(String userId, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.RESOURCE_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.RESOURCE_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        ResourceExample example = new ResourceExample();
        example.or()
                .andUserIdEqualTo(Integer.valueOf(userId));
        List<Resource> list = resourceMapper.selectByExample(example);

        for (Resource resource : list) {

            String createDateStr = resource.getCreateDate();
            if (createDateStr != null) {

                String[] dateTimeParts = createDateStr.split(" ");
                String datePart = dateTimeParts[0]; // "yyyy-MM-dd"
                String timePart = dateTimeParts.length > 1 ? dateTimeParts[1] : "";

                String[] dateParts = datePart.split("-");

                resource.setYear(dateParts[0] + "年");

                resource.setDay(dateParts[1] + "月" + dateParts[2] + "日 " + timePart);
            }
        }
        PageInfo<Resource> resourcePage = new PageInfo<>(list);
        return resourcePage;
    }

    @Override
    public Resource findById(String id) {
        Resource resource = resourceMapper.selectByPrimaryKey(Integer.valueOf(id));
        return resource;
    }

    @Override
    public void updateByRe(String id, String title, CommonsMultipartFile file, String costType, String costNumber, HttpSession session) throws RequestParameterErrorException, FileUploadErrorException, ResourceErrorException {
        if (ParameterUtil.isNull(title) || ParameterUtil.isNull(id) || ParameterUtil.isNull(costType) || ParameterUtil.isNull(costNumber)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        ResourceExample example = new ResourceExample();
        example.or()
                .andIdNotEqualTo(Integer.valueOf(id))
                .andTitleEqualTo(title);
        List<Resource> resources = resourceMapper.selectByExample(example);
        if (!resources.isEmpty()) {
            throw new ResourceErrorException("该标题已有，更改失败");
        }


        Resource resource = resourceMapper.selectByPrimaryKey(Integer.valueOf(id));
        resource.setTitle(title);
        resource.setCostType(Integer.valueOf(costType));
        resource.setCostNumber(Integer.valueOf(costNumber));
        String oldPath = resource.getPath();
        System.out.println("1111111111111111111111111111111111111111");


        if (file != null && !file.isEmpty()) {
            String filename = file.getOriginalFilename();
            String dateFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String relativePath = "/upload/course/" + dateFolder;
            String realPath = session.getServletContext().getRealPath(relativePath);
            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String path = relativePath + "/" + filename;
            resource.setPath(path);

            try {
                resourceMapper.updateByPrimaryKeySelective(resource);
                file.transferTo(new File(realPath, filename));
                if (oldPath != null) {
                    String oldRealPath = session.getServletContext().getRealPath(oldPath);
                    File oldFile = new File(oldRealPath);
                    if (oldFile.exists()) {
                        oldFile.delete();
                    }
                }
            } catch (IOException e) {
                throw new FileUploadErrorException("上传资源失败");
            }
        } else {
            System.out.println("222222222222222222222222222222");
            resourceMapper.updateByPrimaryKeySelective(resource);
        }
    }

    @Override
    public void addByRe(String title, CommonsMultipartFile file, String costType, String costNumber, HttpSession session) throws RequestParameterErrorException, FileUploadErrorException, ResourceErrorException {
        if (ParameterUtil.isNull(costType) || ParameterUtil.isNull(title) || ParameterUtil.isNull(costNumber) || file.isEmpty()) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        ResourceExample example = new ResourceExample();
        example.or()
                .andTitleEqualTo(title);
        List<Resource> resources = resourceMapper.selectByExample(example);
        if (!resources.isEmpty()) {
            throw new ResourceErrorException("该标题已有，添加失败02");
        }


        String[] f = file.getContentType().split("/");
        String fileType = f[1];
        System.out.println(fileType);
        if (!"mp4".equals(fileType) && !"pdf".equals(fileType)) {

            throw new ResourceErrorException("不能存入该类型文件");
        }
        Resource resource = new Resource();
        User user = (User) session.getAttribute("user");
        resource.setUserId(user.getId());

        resource.setTitle(title);
        resource.setCostType(Integer.valueOf(costType));
        resource.setCostNumber(Integer.valueOf(costNumber));

        resource.setClickCount(0);
        resource.setFileSize((int) file.getSize());
        resource.setCreateDate(new Date());
        resource.setStatus(StatusConstant.RESOURCE_STATUS_DISABLED);
        resource.setOriginalName(file.getOriginalFilename());
        resource.setFileType(fileType);


        String filename = file.getOriginalFilename();
        String dateFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String relativePath = "/upload/course/" + dateFolder;


        String realPath = session.getServletContext().getRealPath(relativePath);
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String path = relativePath + "/" + filename;
        resource.setPath(path);

        try {
            resourceMapper.insertSelective(resource);
            File targetFile = new File(dir, filename);
            file.transferTo(targetFile);
        } catch (Exception e) {
            throw new FileUploadErrorException("添加资源失败");
        }

    }

    @Override
    public void deleteByRe(String id, HttpSession session) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        String oldPath = resourceMapper.selectByPrimaryKey(Integer.valueOf(id)).getPath();
        if (oldPath != null) {
            String oldRealPath = session.getServletContext().getRealPath(oldPath);
            File oldFile = new File(oldRealPath);
            if (oldFile.exists()) {
                oldFile.delete();
            }
        }

        resourceMapper.deleteByPrimaryKey(Integer.valueOf(id));
    }

    @Override
    public boolean yesOrNo(String userId, String resourceId) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(resourceId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        UserResourceExample example = new UserResourceExample();
        example.or()
                .andUserIdEqualTo(Integer.valueOf(userId))
                .andResourceIdEqualTo(Integer.valueOf(resourceId));
        List<UserResource> userResources = userResourceMapper.selectByExample(example);
        if (userResources.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void addBuyResource(String userId, String resourceId,HttpSession session) throws RequestParameterErrorException, UserResourceErrorException, GoldPointsErrorException {
        if (ParameterUtil.isNull(resourceId) || ParameterUtil.isNull(userId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        Resource resource = resourceMapper.selectByPrimaryKey(Integer.valueOf(resourceId));
        // 卖家
        User sellUser = userMapper.selectByPrimaryKey(resource.getUserId());
        GoldPoints sellUserGoldPoints = new GoldPoints();

        // 买家
        User user = goldPointsService.findGoldPoints(userId,session);
        GoldPoints userGoldPoints = new GoldPoints();

        if (StatusConstant.RESOURCE_POINTS == resource.getCostType()) {
            if (user.getAllPoint() >= resource.getCostNumber()) {
                // 买家扣积分
                userGoldPoints.setPointCount(-resource.getCostNumber());
                userGoldPoints.setInfo("购买资源花费的积分");

                // 卖家加积分
                sellUserGoldPoints.setPointCount(resource.getCostNumber());
                sellUserGoldPoints.setInfo(user.getNickname() + "购买资源获得的积分");
            } else {
                throw new GoldPointsErrorException("对不起，您的积分不足，购买失败");
            }
        } else {
            if (user.getAllGold() >= resource.getCostNumber()) {
                // 买家扣金币
                userGoldPoints.setGoldCount(-resource.getCostNumber());
                userGoldPoints.setInfo("购买资源花费的金币");

                // 卖家加金币
                sellUserGoldPoints.setGoldCount(resource.getCostNumber());
                sellUserGoldPoints.setInfo(user.getNickname() + "购买资源获得的金币");
            } else {
                throw new GoldPointsErrorException("对不起，您的金币不足，购买失败");
            }
        }

        userGoldPoints.setUserId(Integer.valueOf(userId));
        userGoldPoints.setCreateDate(new Date());

        sellUserGoldPoints.setUserId(sellUser.getId());
        sellUserGoldPoints.setCreateDate(new Date());

        UserResource userResource = new UserResource();
        userResource.setUserId(Integer.valueOf(userId));
        userResource.setResourceId(Integer.valueOf(resourceId));
        userResource.setCreateDate(new Date());

        goldPointsMapper.insertSelective(sellUserGoldPoints);
        goldPointsMapper.insertSelective(userGoldPoints);
        userResourceMapper.insertSelective(userResource);
    }


}
